//
//  BB_WaterfallLayout.swift
//  瀑布流布局
//
//  Created by 崔博 on 2017/5/8.
//  Copyright © 2017年 崔博. All rights reserved.
//

import UIKit
protocol BB_WaterfallLayoutDataSource: class{
    func numberofCols(_ waterfallLayout: BB_WaterfallLayout) -> Int
    func waterFall(_ waterfall: BB_WaterfallLayout, item: Int) -> CGFloat
}
class BB_WaterfallLayout: UICollectionViewFlowLayout {

    weak var dataSource: BB_WaterfallLayoutDataSource?
    
    fileprivate lazy var cellAttributes : [UICollectionViewLayoutAttributes] = [UICollectionViewLayoutAttributes]()

    fileprivate lazy var cols : Int = {
        return self.dataSource?.numberofCols(self) ?? 2
    }()
    fileprivate lazy var totalHeight: [CGFloat] = Array(repeating: self.sectionInset.top, count: self.cols)
}
// MARK:- 准备布局
extension BB_WaterfallLayout{
    override func prepare() {
        super.prepare()
        
        // 定义摩恩初始时所有cell的位置数据
        
        scrollDirection = .vertical
       // UICollectionViewLayoutAttributes
        let itemCount:Int = (collectionView?.numberOfItems(inSection: 0))!
        
        // 给每一个Cell闯将一个UICollectionViewLayoutAttributes
        let cellWidth: CGFloat = ((collectionView!.bounds.width - sectionInset.right - sectionInset.left) - CGFloat(cols - 1) * minimumInteritemSpacing) / CGFloat(cols)
        
        
        for i in 0..<itemCount {
            // 创建indexPath
            let indexPath = IndexPath(item: i, section: 0)
            
            // 创建对应的UICollectionViewLayoutAttributes
            let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
            // 设置attributefrma
            guard let cellHeight: CGFloat = dataSource?.waterFall(self, item: i) else {
                fatalError("请实现数据源方法")
            }
            let minH = totalHeight.min()!
            let minIndex = totalHeight.index(of: minH)!
            let cellX: CGFloat = sectionInset.left + (minimumInteritemSpacing + cellWidth) * CGFloat(minIndex)
            let cellY: CGFloat = minH + minimumLineSpacing
            attributes.frame = CGRect(x: cellX, y: cellY, width: cellWidth, height: cellHeight)
            
            print(cellWidth)
            // 保存attr
            cellAttributes.append(attributes)
            
            // 添加当前高度
            totalHeight[minIndex] = minH + minimumLineSpacing + cellHeight
        }
    }
}
// MARK:- 返回准备好所有布局
extension BB_WaterfallLayout{
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        return cellAttributes
    }
}
// MARK:- 设置contentSize
extension BB_WaterfallLayout{
    override var collectionViewContentSize: CGSize{
        return CGSize(width: 0, height: totalHeight.max()! + sectionInset.bottom)
    }
}
